package com.design.util;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;

/**
 * @author leal
 * @title: XMLUtil
 * @projectName DesignMode
 * @description: XML 解析
 * @date 2021/7/21 22:51
 */
public class XMLUtil {
    /**
     * get xml value
     * @param tagName 目标名称
     * @param index 索引
     * @return value
     */
    public static Object getValueByTagName(String tagName, int index,boolean object){
        try {
            DocumentBuilderFactory documentBuilderFactory=DocumentBuilderFactory.newInstance();
            DocumentBuilder builder=documentBuilderFactory.newDocumentBuilder();
            //202112\design\demo\res\config.xml
            Document doc = builder.parse(new File(("design/src/main/resources/config.xml")));
            // get node
            NodeList nodeList=doc.getElementsByTagName(tagName);
             if (object){
                 // JDK 1.9
                return Class.forName(nodeList.item(index).getFirstChild().getNodeValue()).getDeclaredConstructor().newInstance();
                //JDK 1.9 after
//                 return class.getDeclaredConstructor(String.class).newInstance(nodeList.item(index).getFirstChild().getNodeValue());
            }else{
                 return nodeList.item(index).getFirstChild().getNodeValue().trim();
             }
        }
        catch (Exception ex){
            ex.printStackTrace();
            return null;
        }
    }
}
